package com.bd.rj.backstage.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bd.rj.backstage.service.impl.UserServiceImpl;
import com.bd.rj.common.entity.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserServiceImpl userService;

    /**
     * 查询所有的用户信息
     * @param pageNum
     * @return
     */
    @RequestMapping(value = "/queryall",method = RequestMethod.GET)
    public PageInfo<User> queryAll(@RequestParam(value = "pagenum",defaultValue = "1") int pageNum){
        PageHelper.startPage(pageNum, 10);
        List<User> list = userService.list();
        PageInfo<User> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
    return pageInfo;
    }

    /**
     * 根据id查询用户信息
     * @param pageNum
     * @param id
     * @return
     */
    @RequestMapping(value = "/getquery",method = RequestMethod.GET)
    public IPage<User> query(@RequestParam(value = "pagenum",defaultValue = "1") int pageNum, @RequestParam(value = "id") Long id){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        IPage<User> userByPage = userService.getUserByPage(pageNum, queryWrapper);
        return userByPage;
    }

    /**
     * 删除用户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "delete",method = RequestMethod.DELETE)
    public Map<String,Object> delete(Long[] id){
        Map<String,Object> map = new HashMap<>();
        String result=userService.deleteUser(id);
        map.put("code",200);
        map.put("msg","删除用户");
        map.put("data",result);
        return map;
    }


    /**
     * 查询所用用户信息包括角色，多表联查
     *
     @param pageNum
     页码
     *
     @param pageSize
     每页大小
     *
     @return
     包含查询结果的 Map
     */
//    @RequestMapping(value = "/queryrole", method = RequestMethod.GET)
//    public Map<String, Object> queryrole(
//            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
//            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
//        // 获取角色列表的第一个角色
//        String s = StpUtil.getRoleList().get(0);
//        // 创建分页对象，传入当前页码和每页大小
//        IPage<Map<String, Object>> page = new Page<>(pageNum, pageSize);
//        List<Map<String, Object>> list = null;
//        if (s.equals("1")) {
//            // 当角色为 1 时，可能需要添加额外的逻辑，比如只显示特定数据
//            // 这里假设不添加额外条件，直接调用服务层的分页查询方法
//            page= userService.queryrole(page);
//        } else {
//            // 当角色不为 1 时，调用服务层的分页查询方法并添加排除条件
//            page= userService.queryroleExcludeRole1(page);
//        }
//        Map<String, Object> map = new HashMap<>();
//        map.put("code", 200);
//        map.put("msg", "查询成功");
//        map.put("data", page);
//        return map;
//    }
//
    @RequestMapping(value = "/queryrole", method = RequestMethod.GET)
    public Map<String, Object> queryrole(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        // 创建分页对象，传入当前页码和每页大小
        IPage<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        // 调用服务层的分页查询方法，获取分页结果
        IPage<Map<String, Object>> result = userService.queryrole(page);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", result);
        return map;
    }


    /**
     * 根据角色信息查询用户
     * @return
     */
    @RequestMapping(value = "/queryrolename", method = RequestMethod.GET)
    public Map<String, Object> queryrolename(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            String rname) {
        // 创建分页对象，传入当前页码和每页大小
        IPage<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        // 调用服务层的分页查询方法，传入分页对象和角色名称参数，获取分页结果
        IPage<Map<String, Object>> result = userService.queryrolename(page, rname);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", result);
        return map;
    }

    /**
     * 根据用户状态查询用户
     * @param status
     * @return
     */
    @RequestMapping(value = "/querystatus", method = RequestMethod.GET)
    public Map<String, Object> querystatus(
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            Integer status) {
        // 创建分页对象，传入当前页码和每页大小
        IPage<Map<String, Object>> page = new Page<>(pageNum, pageSize);
        // 调用服务层的分页查询方法，传入分页对象和状态参数，获取分页结果
        IPage<Map<String, Object>> result = userService.querystatus(page, status);

        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", result);
        return map;
    }

    /**
     * 根据姓名查询用户
     * @param username
     * @return
     */
    @RequestMapping(value = "/queryuname",method = RequestMethod.GET)
    public Map queryuname(
            @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
            @RequestParam(value = "pageSize",defaultValue = "1") int pageSize,
            String username){
        // 创建分页对象，传入当前页码和每页大小
        IPage<Map<String,Object>> page = new Page<>(pageNum,pageSize);
        // 调用服务层的分页查询方法，传入分页对象和状态参数，获取分页结果
        IPage<Map<String,Object>> result = userService.queryuname(page,username);
        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","查询成功");
        map.put("data",result);
        return map;
    }

    @RequestMapping(value = "/query",method = RequestMethod.GET)
    public Map<String,Object> queryCondition(
            @RequestParam(value = "pagenum", defaultValue = "1") int pagenum, @RequestParam(value = "pagesize", defaultValue = "10") int pageSize,
            @RequestParam(value = "username",required = false) String username,
            @RequestParam(value = "rname",required = false) String rname
    ){
        Map<String,Object> map = new HashMap<>();
        map.put("username",username);
        map.put("rname",rname);
        IPage<Map> userIPage = userService.getEnterpriseByConditionAndPage(pagenum,pageSize,map);
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", userIPage);
        return map;
    }

    /**
     * 导出用户数据
     * @param id 前端传入的用户ID数组
     * @param response HttpServletResponse对象，用于设置响应相关信息
     */
    @RequestMapping(value = "/excel/export", method = RequestMethod.GET)
    public void exportUserById(@RequestParam("id") Long[] id, HttpServletResponse response) {
        // 调用服务层方法获取导出数据（包含表头映射和用户数据列表）
        Map<String, Object> exportData = userService.getUserDataForExport(id);
        LinkedHashMap<String, String> titleMap = (LinkedHashMap<String, String>) exportData.get("titleMap");
        List<String[]> dataList = (List<String[]>) exportData.get("dataList");

        // 创建工作簿，这里使用XSSFWorkbook支持数据量导出
        XSSFWorkbook workbook = new XSSFWorkbook();

        // 创建工作表
        XSSFSheet sheet = workbook.createSheet("用户信息表");

        // 创建表头行
        int colIndex = 0;
        Row headerRow = sheet.createRow(0);
        for (String key : titleMap.keySet()) {
            Cell cell = headerRow.createCell(colIndex++);
            cell.setCellValue(titleMap.get(key));
        }

        // 填充数据行
        int rowIndex = 1;
        for (String[] rowData : dataList) {
            Row dataRow = sheet.createRow(rowIndex++);
            colIndex = 0;
            for (String cellData : rowData) {
                dataRow.createCell(colIndex++).setCellValue(cellData);
            }
        }

        // 设置响应头，告知浏览器下载的是Excel文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        try {
            // 设置文件名，进行编码防止中文乱码等问题
            String fileName = URLEncoder.encode("用户信息表.xlsx", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 获取输出流，将工作簿写入响应输出流
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Map<String,Object> addUser(@RequestBody User user){
        boolean result = userService.save(user);
        Long userId = user.getId();
        userService.insertUserRole(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("code",200);
        map.put("msg","添加成功");
        map.put("data",result);
        return map;
    }

    /**
     * 批量添加用户数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/excel/add",method = RequestMethod.POST)
    public ResponseEntity<?> importExcel(MultipartHttpServletRequest request) {
        Iterator<String> fileNames = request.getFileNames();
        MultipartFile excelFile = null;
        Map<String,Object> map = new HashMap<>();
        while (fileNames.hasNext()) {
            excelFile = request.getFile(fileNames.next());
        }
        if (excelFile.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请选择要上传的Excel文件");
        }
        try {
            // 解析Excel文件获取用户列表
            List<User> userList = parseExcel(excelFile);
            // 调用服务层方法批量导入用户及关联角色（rid为2）
            boolean result = userService.saveBatch(userList);
            System.out.println(userList);
            userList.forEach(u->{
                userService.batchImportUsers(u.getId());
            });
//            long userId = user.getId();
//            userService.batchImportUsers(userId);

            if (result) {
                map.put("code",200);
                map.put("msg","Excel文件中的用户数据导入成功");
                map.put("data",userList);
                return ResponseEntity.ok(map);
            } else {
                map.put("code",500);
                map.put("msg", "用户数据导入失败，请检查数据格式或联系管理员");
                map.put("data","error");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
            }
        } catch (Exception e) {
            map.put("code",500);
            map.put("msg", "导入过程出现异常：" + e.getMessage());
            map.put("data","error");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(map);
        }

    }

    private List<User> parseExcel(MultipartFile excelFile) throws Exception {
        // 此处使用Apache POI来解析Excel文件
        List<User> userList = new ArrayList<>();
        // 获取输入流
        try (InputStream inputStream = excelFile.getInputStream()) {
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            // 遍历行（跳过标题行，假设第一行是标题）
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                User user = new User();
                // 根据Excel列顺序和内容设置User对象属性
                Cell usernameCell = row.getCell(0);
                if (usernameCell!= null) {
                    user.setUsername(usernameCell.getStringCellValue());
                }
                Cell passwordCell = row.getCell(1);
                if (passwordCell!= null) {
                    user.setPassword(passwordCell.getStringCellValue());
                }
                Cell realnameCell = row.getCell(2);
                if (realnameCell!= null) {
                    user.setRealname(realnameCell.getStringCellValue());
                }
                Cell phoneCell = row.getCell(3);
                phoneCell.setCellType(CellType.STRING);
                if (phoneCell!= null) {
                    user.setPhone(phoneCell.getStringCellValue());
                }
                Cell emailCell = row.getCell(4);
                if (emailCell!= null) {
                    user.setEmail(emailCell.getStringCellValue());
                }
                Cell professionCell = row.getCell(5);
                if (professionCell!= null) {
                    user.setProfession(professionCell.getStringCellValue());
                }
                Cell createtimeCell = row.getCell(6);
                if (createtimeCell!= null) {
                    user.setCreatetime(createtimeCell.getDateCellValue());
                }
                Cell sexCell = row.getCell(7);
                if (sexCell!= null) {
                    user.setSex(sexCell.getStringCellValue());
                }
                Cell urlCell = row.getCell(8);
                if (urlCell!= null) {
                    user.setUrl(urlCell.getStringCellValue());
                }
                userList.add(user);
            }
        }
        return userList;
    }
}
